﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using MessageLibrary;

namespace GamedataLibrary
{
    /// <summary>
    /// Trida starajici se o komunikaci serveru.
    /// </summary>
    class ServerCommunication
    {
        #region Fields

        Server server;
        Socket socket;
        byte[] buffer;
        Thread receiveThread;

        int type;
        MessageLibrary.Messages.Message message;

        #endregion // Fields

        #region Properties

        /// <summary>
        /// Vrati buffer prijatych dat.
        /// </summary>
        public byte[] Buffer { get { return buffer; } }

        /// <summary>
        /// Typ prijate zpravy.
        /// </summary>
        public int Type { get { return type; } }

        /// <summary>
        /// Deserializovana prijata zprava.
        /// </summary>
        public MessageLibrary.Messages.Message Message { get { return message; } }

        #endregion // Properties


        public ServerCommunication(Server server, Socket socket)
        {
            this.server = server;
            this.socket = socket;
        }

        /// <summary>
        /// Prijme paket od klienta.
        /// </summary>
        public void Receive()
        {
            // pred kazdym Receive vyprazdnime buffer
            this.buffer = new byte[1024];

            receiveThread = new Thread(Listen);

            receiveThread.Start();
        }

        /// <summary>
        /// Posloucha v oddelenem threadu na Receive dat od klienta.
        /// </summary>
        private void Listen()
        {
            try
            {
                socket.Receive(buffer);

                MessageLibrary.MessageComposer.Deserialize(buffer, out type, out message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void Join()
        {
            this.receiveThread.Join();
        }

        /// <summary>
        /// Posle packet ze serveru klientovi.
        /// </summary>
        /// <param name="buffer"></param>
        public void Send(byte[] buffer)
        {
            socket.Send(buffer);
        }
    }
}
